<?php
// 确保目录存在
function ensure_directories() {
    $dirs = ['temp', 'downloads'];
    foreach ($dirs as $dir) {
        if (!file_exists($dir)) {
            mkdir($dir, 0755, true);
        }
    }
    
    $today = date('Ymd');
    // $tempDir = "temp/{$today}";
    $tempDir = "../{$_COOKIE['enorg']}-output/temp/{$today}";
    if (!file_exists($tempDir)) {
        mkdir($tempDir, 0755, true);
    }
}

// 加载API密钥
function load_api_keys() {
    $apiKeys = [];
    $apiKeyFile = $_COOKIE['enorg'].'-BIZYAIR_API_KEY.env';
    
    // 从环境变量加载
    if (!empty(getenv('BIZYAIR_API_KEY'))) {
        $apiKeys[] = trim(getenv('BIZYAIR_API_KEY'));
    }
    
    // 从文件加载
    if (file_exists($apiKeyFile)) {
        $lines = file($apiKeyFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        foreach ($lines as $line) {
            $key = trim($line);
            if (!empty($key)) {
                $apiKeys[] = $key;
            }
        }
    }
    
    // 去重
    return array_values(array_unique($apiKeys));
}

// 保存API密钥
function save_api_key($apiKey) {
    $apiKey = trim($apiKey);
    if (empty($apiKey)) {
        return "API密钥不能为空";
    }
    
    $apiKeys = load_api_keys();
    if (in_array($apiKey, $apiKeys)) {
        return "API密钥已存在，当前共有 " . count($apiKeys) . " 个密钥";
    }
    
    // 新密钥优先
    array_unshift($apiKeys, $apiKey);
    
    $apiKeyFile = $_COOKIE['enorg'].'-BIZYAIR_API_KEY.env';
    file_put_contents($apiKeyFile, implode("\n", $apiKeys) . "\n");
    
    return "API密钥已保存，当前共有 " . count($apiKeys) . " 个密钥";
}

// 获取当前API密钥
function get_current_api_key($customKey = "") {
    $customKey = trim($customKey);
    if (!empty($customKey)) {
        save_api_key($customKey);
        return $customKey;
    }
    
    $apiKeys = load_api_keys();
    if (empty($apiKeys)) {
        return "";
    }
    
    // 简单的轮询机制
    $index = isset($_SESSION['current_key_index']) ? $_SESSION['current_key_index'] : 0;
    $currentKey = $apiKeys[$index];
    $_SESSION['current_key_index'] = ($index + 1) % count($apiKeys);
    
    return $currentKey;
}

// 加载JSON文件夹中的所有配置
function load_json_configs() {
    $jsonDir = __DIR__ . '/json/';
    $jsonFiles = glob($jsonDir . '*.json');
    $configs = [];
    
    foreach ($jsonFiles as $file) {
        $content = file_get_contents($file);
        if ($content) {
            $json = json_decode($content, true);
            if ($json && isset($json['id']) && isset($json['name']) && isset($json['web_app_id'])) {
                $filename = basename($file);
                $configs[$json['id']] = [
                    'filename' => $filename,
                    'id' => $json['id'],
                    'name' => $json['name'],
                    'web_app_id' => $json['web_app_id'],
                    'input_values' => $json['input_values'] ?? [],
                    'url_images' => $json['url_images'] ?? '',
                    'info' => $json['info'] ?? ''
                ];
            }
        }
    }
    
    return $configs;
}

// 图片转换为WebP的base64编码
function image_to_webp_base64($imagePath) {
    try {
        if (!file_exists($imagePath)) {
            throw new Exception("图片文件不存在: {$imagePath}");
        }
        
        $imageInfo = getimagesize($imagePath);
        $mime = $imageInfo['mime'];
        
        // 根据MIME类型创建图像资源
        switch ($mime) {
            case 'image/jpeg':
                $image = imagecreatefromjpeg($imagePath);
                break;
            case 'image/png':
                $image = imagecreatefrompng($imagePath);
                // 处理透明背景
                imagealphablending($image, false);
                imagesavealpha($image, true);
                break;
            case 'image/gif':
                $image = imagecreatefromgif($imagePath);
                break;
            case 'image/webp':
                // 添加对WebP格式的支持
                if (function_exists('imagecreatefromwebp')) {
                    $image = imagecreatefromwebp($imagePath);
                } else {
                    throw new Exception("PHP版本不支持WebP格式处理");
                }
                break;
            default:
                throw new Exception("不支持的图片格式: {$mime}");
        }
        
        // 转换为RGB
        $width = imagesx($image);
        $height = imagesy($image);
        $rgbImage = imagecreatetruecolor($width, $height);
        
        // 白色背景
        $white = imagecolorallocate($rgbImage, 255, 255, 255);
        imagefill($rgbImage, 0, 0, $white);
        
        // 合并图像
        imagecopy($rgbImage, $image, 0, 0, 0, 0, $width, $height);
        
        // 保存为WebP到临时文件
        $today = date('Ymd');
        $timestamp = date('His');

        $tempPath = "../{$_COOKIE['enorg']}-output/temp/{$today}/{$_COOKIE['NAME']}_{$timestamp}.webp";

        imagewebp($rgbImage, $tempPath, 95);
        
        // 转换为base64
        ob_start();
        imagewebp($rgbImage, null, 95);
        $imageData = ob_get_clean();
        $base64 = base64_encode($imageData);
        
        // 释放资源
        imagedestroy($image);
        imagedestroy($rgbImage);
        
        return [
            "data:image/webp;base64,{$base64}",
            $tempPath
        ];
    } catch (Exception $e) {
        throw new Exception("图片处理失败: " . $e->getMessage());
    }
}

// 下载图片并生成缩略图
function download_image($url, $filename) {
    try {
        $ch = curl_init($url);
        $filepath = "../{$_COOKIE['enorg']}-output/BizyAIR/{$_COOKIE['NAME']}_{$filename}";
        
        $file = fopen($filepath, 'w');
        curl_setopt($ch, CURLOPT_FILE, $file);
        curl_setopt($ch, CURLOPT_TIMEOUT, 300);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        
        $result = curl_exec($ch);
        
        if (curl_errno($ch)) {
            throw new Exception("下载失败: " . curl_error($ch));
        }
        
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($httpCode != 200) {
            throw new Exception("下载失败，HTTP状态码: {$httpCode}");
        }
        
        curl_close($ch);
        fclose($file);
        
        // 生成300px宽度的WebP缩略图
        $thumbnailFilename = str_replace('.png', '-thumb.webp', $filename);
        $thumbnailPath = "../{$_COOKIE['enorg']}-output/BizyAIR/{$_COOKIE['NAME']}_{$thumbnailFilename}";
        
        $sourceImage = imagecreatefrompng($filepath);
        if ($sourceImage) {
            $originalWidth = imagesx($sourceImage);
            $originalHeight = imagesy($sourceImage);
            
            $thumbnailWidth = 300;
            $thumbnailHeight = intval(($originalHeight * $thumbnailWidth) / $originalWidth);
            
            $thumbnailImage = imagecreatetruecolor($thumbnailWidth, $thumbnailHeight);
            
            imagealphablending($thumbnailImage, false);
            imagesavealpha($thumbnailImage, true);
            
            imagecopyresampled(
                $thumbnailImage, $sourceImage,
                0, 0, 0, 0,
                $thumbnailWidth, $thumbnailHeight,
                $originalWidth, $originalHeight
            );
            
            imagewebp($thumbnailImage, $thumbnailPath, 85);
            
            imagedestroy($sourceImage);
            imagedestroy($thumbnailImage);
            
            error_log("成功生成缩略图: " . $thumbnailPath);
        } else {
            error_log("无法从PNG文件创建图像资源: " . $filepath);
        }
        
        return $filepath;
    } catch (Exception $e) {
        throw new Exception("下载图片失败: " . $e->getMessage());
    }
}

// 保存日志
function save_log($filename, $data, $uploadedImages, $requestId, $outputs) {
    $logData = [
        "timestamp" => date('c'),
        "request_data" => $data,
        "uploaded_images" => $uploadedImages,
        "request_id" => $requestId,
        "outputs" => $outputs
    ];
    
    $logFile = "../{$_COOKIE['enorg']}-output/BizyAIR/{$_COOKIE['NAME']}_{$filename}.log";
    try {
        file_put_contents($logFile, json_encode($logData, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
        return $logFile;
    } catch (Exception $e) {
        return "保存日志失败: " . $e->getMessage();
    }
}

// 处理API请求
function process_api_request() {
    ensure_directories();

    // 加载JSON配置以确定需求
    $jsonConfigs = load_json_configs();
    $selectedType = $_POST['input_type'] ?? '';
    $currentGeneratedConfig = null;
    foreach ($jsonConfigs as $config) {
        if ($config['name'] === $selectedType) {
            $currentGeneratedConfig = generate_type_config($config);
            break;
        }
    }

    if (!$currentGeneratedConfig) {
        return [
            'status' => 'error',
            'message' => '无法加载所选模型的配置。',
            'data' => [],
            'image' => ''
        ];
    }
    
    $apiKey = $_POST['api_key'] ?? '';
    $webAppId = $_POST['web_app_id'] ?? '';
    $inputType = $_POST['input_type'] ?? '';
    
    $textPrompt = $_POST['text_prompt'] ?? '';
    $textPromptField = $_POST['text_prompt_field'] ?? '';
    
    $imageFields = [];
    for ($i = 1; $i <= 5; $i++) {
        $imageFields[$i] = [
            'file' => $_FILES["image_{$i}"] ?? null,
            'url' => $_POST["image_url_{$i}"] ?? '',
            'field' => $_POST["image_{$i}_field"] ?? ''
        ];
    }
    
    $floatValue = $_POST['float_value'] ?? 2;
    $floatField = $_POST['float_field'] ?? '';
    
    // 处理多个整数参数
    $intValues = [];
    $intFields = [];
    
    if (isset($_POST['int_value']) && is_array($_POST['int_value'])) {
        // 处理新的多整数参数格式
        foreach ($_POST['int_value'] as $index => $value) {
            if (isset($_POST['int_field'][$index])) {
                $intValues[$index] = $value;
                $intFields[$index] = $_POST['int_field'][$index];
            }
        }
    } else {
        // 兼容旧版本，只处理一个整数参数
        $intValue = $_POST['int_value'] ?? 88888;
        $intField = $_POST['int_field'] ?? '';
        if (!empty($intField)) {
            $intValues[0] = $intValue;
            $intFields[0] = $intField;
        }
    }
    
    $resolutionValue = $_POST['resolution_value'] ?? '';
    $resolutionField = $_POST['resolution_field'] ?? '';
    $sizeValue = $_POST['size_value'] ?? '';
    $sizeField = $_POST['size_field'] ?? '';
    
    try {
        // 获取API密钥
        $currentApiKey = get_current_api_key($apiKey);
        if (empty($currentApiKey)) {
            return [
                'status' => 'error',
                'message' => '未找到有效的API密钥',
                'data' => [],
                'image' => ''
            ];
        }
        
        // 构建基础数据
        $data = [
            "web_app_id" => intval($webAppId),
            "suppress_preview_output" => true,
            "input_values" => []
        ];
        
        // 处理图片输入
        $uploadedImages = [];
        $requiredImageCount = $currentGeneratedConfig['images'] ?? 0;
        $allImageSources = [];
        
        error_log("POST数据: " . json_encode($_POST, JSON_UNESCAPED_UNICODE));
        error_log("FILES数据: " . json_encode($_FILES, JSON_UNESCAPED_UNICODE));
        
        // 处理上传的图片 - 检查所有激活的图片区域
        for ($i = 1; $i <= 5; $i++) {
            if ($i > $requiredImageCount) {
                break;
            }
            
            $image = $imageFields[$i];
            $hasValidFile = false;
            $sourcePath = '';
            
            // 检查文件上传
            if (!empty($image['file']) && isset($image['file']['error']) && $image['file']['error'] == UPLOAD_ERR_OK) {
                $tempFile = $image['file']['tmp_name'];
                if (!empty($tempFile) && is_uploaded_file($tempFile)) {
                    $fileInfo = @getimagesize($tempFile);
                    if ($fileInfo !== false) {
                        $today = date('Ymd');
                        $filename = uniqid() . '_' . basename($image['file']['name']);
                        $timestamp = date('His');
                        $sourcePath = "../{$_COOKIE['enorg']}-output/temp/{$today}/{$_COOKIE['NAME']}_{$timestamp}-{$filename}";
                        
                        if (move_uploaded_file($tempFile, $sourcePath)) {
                            $hasValidFile = true;
                        }
                    }
                }
            }
            
            // 检查URL
            $hasValidUrl = false;
            $url = trim($image['url'] ?? '');
            if (!$hasValidFile && !empty($url) && (strpos($url, 'http://') === 0 || strpos($url, 'https://') === 0)) {
                $hasValidUrl = true;
            }
            
            // 收集图片源
            if ($hasValidFile) {
                $allImageSources[] = [
                    'path' => $sourcePath,
                    'type' => 'file',
                    'field' => $image['field']
                ];
            } elseif ($hasValidUrl) {
                $allImageSources[] = [
                    'path' => $url,
                    'type' => 'url',
                    'field' => $image['field']
                ];
            }
        }
        
        // 检查图片数量
        if (count($allImageSources) < $requiredImageCount) {
            $errorMessage = "{$inputType}需要{$requiredImageCount}张图片，但只检测到" . count($allImageSources) . "张。请在激活的图片区域中上传足够的图片。";
            return [
                'status' => 'error',
                'message' => $errorMessage,
                'data' => [],
                'image' => ''
            ];
        }
        
        // 处理图片
        foreach ($allImageSources as $index => $source) {
            try {
                if ($source['type'] == 'file') {
                    list($base64Data, $tempPath) = image_to_webp_base64($source['path']);
                    $data['input_values'][$source['field']] = $base64Data;
                    $uploadedImages[] = "本地文件: " . $source['path'];
                } elseif ($source['type'] == 'url') {
                    $data['input_values'][$source['field']] = $source['path'];
                    $uploadedImages[] = "URL: " . $source['path'];
                }
            } catch (Exception $e) {
                return [
                    'status' => 'error',
                    'message' => "图片处理失败: " . $e->getMessage(),
                    'data' => [],
                    'image' => ''
                ];
            }
        }
        
        // 添加文本提示词
        if (!empty(trim($textPrompt)) && !empty(trim($textPromptField))) {
            $data['input_values'][trim($textPromptField)] = trim($textPrompt);
        }
        
        // 添加数值参数
        if ($currentGeneratedConfig['float'] && !empty(trim($floatField))) {
            $data['input_values'][trim($floatField)] = strval(floatval($floatValue));
        }
        
        // 添加整数参数
        foreach ($intValues as $index => $value) {
            if (!empty(trim($intFields[$index]))) {
                $data['input_values'][trim($intFields[$index])] = strval(intval($value));
            }
        }
        
        // 添加分辨率参数
        if (!empty(trim($resolutionValue)) && !empty(trim($resolutionField))) {
            $data['input_values'][trim($resolutionField)] = trim($resolutionValue);
        }
        
        // 添加尺寸参数
        if (!empty(trim($sizeValue)) && !empty(trim($sizeField))) {
            $data['input_values'][trim($sizeField)] = trim($sizeValue);
        }
        
        // 发送API请求
        $apiUrl = "https://api.bizyair.cn/w/v1/webapp/task/openapi/create";
        $headers = [
            "Content-Type: application/json",
            "Authorization: Bearer {$currentApiKey}"
        ];
        
        $ch = curl_init($apiUrl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 600);
        
        $response = curl_exec($ch);
        
        if (curl_errno($ch)) {
            throw new Exception("API请求失败: " . curl_error($ch));
        }
        
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($httpCode != 200) {
            throw new Exception("API请求失败，HTTP状态码: {$httpCode}，响应: {$response}");
        }
        
        curl_close($ch);
        $result = json_decode($response, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception("API响应解析失败: " . json_last_error_msg());
        }
        
        $requestId = $result['request_id'] ?? '';
        $outputs = $result['outputs'] ?? [];
        
        if (empty($outputs)) {
            return [
                'status' => 'warning',
                'message' => "API调用成功但未返回图片",
                'data' => $result,
                'image' => ''
            ];
        }
        
        // 下载生成的图片
        $downloadedImages = [];
        foreach ($outputs as $i => $output) {
            if (!empty($output['object_url'])) {
                $filename = count($outputs) > 1 
                    ? sprintf("%s_%02d.png", $requestId, $i + 1) 
                    : "{$requestId}.png";
                
                $imageUrl = $output['object_url'];
                $downloadedImages[] = $imageUrl;
                
                $downloadedPath = download_image($output['object_url'], $filename);
                
                $txtFilename = str_replace('.png', '.txt', $filename);
                $txtContent = "图片URL: {$imageUrl}\n";
                $txtContent .= "本地保存路径: {$downloadedPath}\n";
                $thumbnailFilename = str_replace('.png', '-thumb.webp', $filename);
                $thumbnailPath = "../{$_COOKIE['enorg']}-output/BizyAIR/{$_COOKIE['NAME']}_{$thumbnailFilename}";
                $txtContent .= "缩略图路径: {$thumbnailPath}\n";
                if (!empty(trim($textPrompt))) {
                    $txtContent .= "中文提示词: " . trim($textPrompt) . "\n";
                    $txtContent .= "英文提示词: " . trim($textPrompt) . "\n";
                }
                $txtContent .= "生成时间: " . date('Y-m-d H:i:s') . "\n";
                $txtContent .= "功能类型: {$inputType}\n";
                $txtContent .= "API URL: {$output['object_url']}\n";
                
                file_put_contents("../{$_COOKIE['enorg']}-output/BizyAIR/{$_COOKIE['NAME']}_{$txtFilename}", $txtContent);
            }
        }
        
        // 保存日志
        if (!empty($downloadedImages)) {
            save_log($requestId, $data, $uploadedImages, $requestId, $outputs);
        }
        
        $message = "✅ 生成成功!\n";
        $message .= "任务ID: {$requestId}\n";
        $message .= "生成图片数量: " . count($outputs) . "\n";
        foreach ($outputs as $i => $output) {
                $message .= "图片 " . ($i+1) . " URL: {$output['object_url']}\n";
        }
        
        $firstImage = !empty($downloadedImages) ? $downloadedImages[0] : '';
            
        return [
            'status' => 'success',
            'message' => $message,
            'data' => $result,
            'image' => $firstImage
        ];
        
    } catch (Exception $e) {
        return [
            'status' => 'error',
            'message' => $e->getMessage(),
            'data' => [],
            'image' => ''
        ];
    }
}

// 处理表单提交
$response = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'process') {
    $response = process_api_request();
}

// 根据JSON配置生成类型配置
function generate_type_config($jsonConfig) {
    $config = [
        'web_app_id' => $jsonConfig['web_app_id'],
        'text' => false,
        'float' => false,
        'int' => false,
        'image_fields' => [],
        'text_field' => '',
        'float_field' => '',
        'int_field' => '',
        'int_fields' => [], // 用于存储所有整数字段
        'resolution' => false,
        'resolution_field' => '',
        'size' => false,
        'size_field' => ''
    ];
    
    $imageCount = 0;
    if (isset($jsonConfig['input_values'])) {
        foreach ($jsonConfig['input_values'] as $key => $value) {
            // 图片类型字段
            if (strpos($key, 'LoadImage.image') !== false) {
                $config['image_fields'][] = $key;
                $imageCount++;
            } 
            // 文本类型字段
            elseif (strpos($key, 'TextEncodeQwenImageEditPlus.prompt') !== false ||
                   strpos($key, 'TextEncodeQwenImageEdit.prompt') !== false ||
                   strpos($key, 'Text Multiline.text') !== false ||
                   strpos($key, 'CLIPTextEncode.text') !== false ||
                   strpos($key, 'PrimitiveStringMultiline.value') !== false) {
                $config['text'] = true;
                $config['text_field'] = $key;
            } 
            // 浮点类型字段
            elseif (strpos($key, 'easy float.value') !== false || 
                   strpos($key, 'ImageScaleBy.scale_by') !== false) {
                $config['float'] = true;
                $config['float_field'] = $key;
            } 
            // 整数类型字段
            elseif (strpos($key, 'SDXLEmptyLatentSizePicker+.batch_size') !== false ||
                   strpos($key, 'PrimitiveInt.value') !== false ||
                   strpos($key, 'KSampler.steps') !== false ||
                   strpos($key, 'EmptySD3LatentImage.width') !== false ||
                   strpos($key, 'EmptySD3LatentImage.height') !== false ||
                   strpos($key, 'EmptySD3LatentImage.batch_size') !== false) {
                $config['int'] = true;
                $config['int_fields'][] = $key; // 将所有整数字段添加到数组中
            }
            // 分辨率字段
            elseif (strpos($key, 'SDXLEmptyLatentSizePicker+.resolution') !== false) {
                $config['resolution'] = true;
                $config['resolution_field'] = $key;
            }
            // 尺寸字段
            elseif (strpos($key, 'BizyAir_Seedream4.size') !== false) {
                $config['size'] = true;
                $config['size_field'] = $key;
            }
        }
    }
    
    $config['images'] = $imageCount;
    return $config;
}

// 加载所有JSON配置
$jsonConfigs = load_json_configs();

// 获取请求的ID
$requestedId = isset($_GET['id']) ? intval($_GET['id']) : array_key_first($jsonConfigs); // 默认ID

// 默认类型和配置
$defaultConfig = $jsonConfigs[$requestedId] ?? reset($jsonConfigs);
$selectedType = $_POST['input_type'] ?? $defaultConfig['name'];

// 生成类型配置
$typeConfig = [];
foreach ($jsonConfigs as $id => $jsonConfig) {
    $typeConfig[$jsonConfig['name']] = generate_type_config($jsonConfig);
}

// 当前配置
$currentConfig = $typeConfig[$selectedType] ?? generate_type_config($defaultConfig);